/*global $, jQuery*/
/*
 *{titles}  : 迷你楼层
 *{author}  : daFei
 **/
var isOnPage = false;
var inputLenth = "";
var inputCounty = "";

(function ($) {
    'use strict';
   
    
    var minFloor = {
        init: function() {
            this.elements();
            this.events();
        },
        elements: function() {
            this.target = $('.min-floor');
            this.floors = $('div[data-floor]');
            this.arr = [];
        },
        events: function() {
            var
                self = this,
                top = 0,
                index = 0;

            $.each(this.floors, function() {
                self.arr.push($(this).offset().top);
            });

            $(window).on('scroll', function() {
                //noinspection JSValidateTypes
                top = $(this).scrollTop();
                var flag = parseInt($('#header').height(), 10) + parseInt($('.focus').height(), 10) - 60;

                if (top > flag) {
                    self.target.addClass('visible');
                } else {
                    self.target.removeClass('visible');
                }
                if (!$('html,body').is(':animated')) {
                    self.changeFloor(self.getFloor(top));
                }
            });

            self.target.on('click', 'a', function() {
                index = $(this).index();
                $('html, body').stop().animate({
                    scrollTop: self.floors.eq(index).offset().top - 20
                });

                self.changeFloor(index);
            });
        },
        changeFloor: function(index) {
            this.target.find('a').removeClass('active');
            this.target.find('a').eq(index).addClass('active');
        },
        getFloor: function(val) {
            var
                i,
                len;

            for (i = 0, len = this.floors.length; i < len; i += 1) {
                if (val < this.arr[0]) {
                    return 0;
                }
                if (val > this.arr[i] && val < this.arr[i + 1]) {
                    return i + 1;
                }
            }
        }
    };

    minFloor.init();
}(jQuery));


// 轮播图调用
$('#js-focus-slide').slide({
    type: 'fade'
});


$('#js-floor-1').slide();
$('#js-floor-2').slide();
$('#js-floor-3').slide();
$('#js-floor-4').slide();
$('#js-floor-5').slide();
$('#js-floor-6').slide();
$('#js-floor-7').slide();
$('#js-brand-kitchen').slide({
    isLoop: false,
    isAuto: false,
    isMarker: false
});
$('#js-brand-washBath').slide({
    isLoop: false,
    isAuto: false,
    isMarker: false
});
$('#js-brand-room').slide({
    isLoop: false,
    isAuto: false,
    isMarker: false
});
$('#js-brand-house').slide({
    isLoop: false,
    isAuto: false,
    isMarker: false
});
$('#js-brand-commercial').slide({
    isLoop: false,
    isAuto: false,
    isMarker: false
});
$('#js-brand-core').slide({
    isLoop: false,
    isAuto: false,
    isMarker: false
});


// 选项卡调用
$('#js-tab-kitchen').tab();
$('#js-tab-washBath').tab();
$('#js-tab-room').tab();
$('#js-tab-house').tab();
$('#js-tab-commercial').tab();
$('#js-tab-core').tab();


//测水质
(function($) {
    'use strict';

    var rotateAngle = {
    	
    	init:function(){
    		this.initArea();
    		//this.initWaterNews();
    		//this.printWaterNews();
    	},

        initArea:function(){
            var that = this;
            that.changeArea(1);

            $("#province").change(function() {
              that.changeArea(2);
              if (this.selectedIndex !== 0) {
                $('.query-water-area').find('.error').hide();
              }
            });


            $("#citySZ").change(function() {
                that.changeArea(3)
              if (this.selectedIndex !== 0) {
                $('.query-water-area').find('.error').hide();
              }
            });

            $("#county").change(function() {
                that.changeArea(4);
              if (this.selectedIndex !== 0) {
                $('.query-water-area').find('.error').hide();
              }
            });


        },

        changeArea:function(AreaLevel) {
            var that = this;
            if (AreaLevel == 4) {
                //水质查询页面改版
                $("#text_search").val("");
            }
            else {
                if(AreaLevel == 1){
                    var provinceJson = '{"Type":0,"Description":"","Data":{"ShuiZhiCityList":["北京","上海","天津","重庆","安徽","福建","甘肃","广东","广西","贵州","海南","河北","河南","黑龙江","湖北","湖南","吉林","江苏","江西","辽宁","内蒙","宁夏","青海","山东","山西","陕西","四川","西藏","新疆","云南","浙江"]},"Rows":{"CityCodeList":["2","10","3","23","13","14","29","20","21","25","22","4","17","9","18","19","8","11","15","7","6","31","30","16","5","28","24","27","32","26","12"]}}';
                    this.printAreaInfo(JSON.parse(provinceJson).Data, JSON.parse(provinceJson).Rows, AreaLevel);
                    return;
                }

                var province = encodeURI($("#province").find("option:selected").text());
                var provinceId = encodeURI($("#province").find("option:selected").val());
                var city = encodeURI($("#citySZ").find("option:selected").text());
                var parentAreaName = province;
                if(AreaLevel == 3){
                    parentAreaName = city;
                }
                if(AreaLevel == 2){
                    parentAreaName = provinceId;
                }
                
                var url = rrs.baseDomain + "ixv5/getArea";

                $.ajax({
                    type: "GET",
                    url: url,
                    dataType: "jsonp",
                    jsonp: "callback",
                    data: { parentAreaName: parentAreaName, areaLevel: AreaLevel },

                    success: function(data) {
                        that.printAreaInfo(data.data, data.rows, AreaLevel);
                    },
                    error: function(e) {
                        //alert("系统繁忙，请稍后重试！");
                        return false;
                    }
                });
            }
        },

        printAreaInfo:function(data, code, level) {
            var $provincePanel = $("#province");
            var $cityPanel = $("#citySZ");
            var $countyPanel = $("#county");
            if (level == 1) {
                $provincePanel.empty();
                $provincePanel.append("<option  value=\"default\">请选择省</option>");
                $cityPanel.empty();
                $cityPanel.append("<option  value=\"default\">请选择市</option>");
                $countyPanel.empty();
                $countyPanel.append("<option  value=\"default\">请选择地区</option>");
            }
            else if (level == 2) {
                $cityPanel.empty();
                $cityPanel.append("<option  value=\"default\">请选择市</option>");
                $countyPanel.empty();
                $countyPanel.append("<option  value=\"default\">请选择地区</option>");
            }
            else {
                $countyPanel.empty();
                $countyPanel.append("<option  value=\"default\">请选择地区</option>");
            }

            if (data != null) {
                if (data.ShuiZhiCityList.length > 0) {
                    var str = "";
                    $.each(data.ShuiZhiCityList, function(index, item) {
                        if (level == 1) {
                            $provincePanel.append("<option  value='" + code.CityCodeList[index] + "'>" + item + "</option>");
                        }
                        else if (level==2) {
                            $cityPanel.append("<option  value='" + code.CityCodeList[index] + "'>" + item + "</option>");
                        }
                        else {
                            $countyPanel.append("<option  value='" + code.CityCodeList[index] + "'>" + item + "</option>");
                        }
                    })
                }
            }
            $("#district_options").empty();
            inputLenth = "";
            inputCounty = "";
        },

        searchVillage:function(){
            var that = this;
            $("#district_options").css("display", "block");

            var countyCode = encodeURI($("#county").find("option:selected").val()).substr(0,4);
            var POI_Name = encodeURI($.trim($("#text_search").val()));

            var county = encodeURI($("#county").find("option:selected").text());

            inputCounty = county;
            inputLenth = POI_Name;

            var url = rrs.baseDomain + "ixv5/villageOrshuiZhi";

            $.ajax({
                type: "GET",
                url: url,
                dataType: "jsonp",
                jsonp: "callback",
                data: { gb_code: countyCode, poi_name: POI_Name, checkFlag: '0' },

                success: function(data) {
                    that.printVillage(data.data);
                },

                error: function() {
                    //alert("系统繁忙，请稍后重试！");
                    return false;
                }
            });

        },
        
        printVillage:function(result){
        	var data = eval("("+result+")");
        	var $district_options = $("#district_options");
        	
        	if (data.data.length > 0) {

                $.each(data.data, function(index, item) {
                  $district_options.append('<li><a class="js-poiName" title="'+item.poi_name+'" href="javascript:selectDistrict(\''+item.poi_name+'\')">'+item.poi_name+'</a></li>');
                })
            }
        },

        printSZInfo:function (result) {
            var $district_options = $("#district_options");
            var data = eval("("+result+")");

            $district_options.empty();

            if (data != null) {
              $('#tds').text(data.data.tds);
              $('#ylz').text(data.data.ylz);
              $("#text_search").val(data.data.poi_name);
              this.setRotate('#js-rotate',$('#tds').text());

              $('.beforecheck').css('display', 'none');
              $('.aftercheck').css('display', 'block');
            }
        },

        getRotate: function(obj, angle) {
            $(obj).stopRotate();
            $(obj).rotate({
                angle: 0,
                animateTo: angle,
                duration: 600
            });
        },

        setRotate: function(obj,tds) {
            //获取TD的值,模拟一个值为55
            var
                self = this,
                tds = Number(tds);

            if (tds > 0 && tds < 2001) {
                if (tds > 0 && tds <= 50) {
                    self.getRotate(obj, 15);
                } else if (tds > 51 && tds <= 100) {
                    self.getRotate(obj, 45);
                } else if (tds > 101 && tds <= 300) {
                    self.getRotate(obj, 75);
                } else if (tds > 301 && tds <= 600) {
                    self.getRotate(obj, 105);
                } else if (tds > 600 && tds <= 1000) {
                    self.getRotate(obj, 135);
                } else if (tds > 1001 && tds <= 2000) {
                    self.getRotate(obj, 165);
                }
            } else {
                self.getRotate(obj, 0);
            }
        },
        
        initWaterNews: function(){
        	var that = this;

            var url = rrs.baseDomain + "ixv5/findWaterNews";

            $.ajax({
                type: "GET",
                url: url,
                dataType: "jsonp",
                jsonp: "callback",

                success: function(data) {
                    that.printWaterNews(data);
                },
                error: function(e) {
                    //alert("系统繁忙，请稍后重试！");
                    return false;
                }
            });
        },
        
        printWaterNews: function(result){
        	var data = result.data;
        	
            var $picArticle = $('.water-pic');
            var $wordPic = $('.water-graphic');
            var $wordArticle = $('.water-list');
            
            var picArticle = data.picArticle;
            var wordPicList = data.wordPicList;
            var wordArticleList = data.wordArticleList;
            
            $picArticle.append("<a href='http://shui.rrs.com/article/articleDetail/" + picArticle.id + ".html' target='_blank'>"
		            +"<img width='400' height='300' src='" + picArticle.imageUrl + "' original='" + picArticle.imageUrl + "' >"
		            +"</a>"
		            +"<p>" + picArticle.title + "</p>");
            
            $.each(wordPicList, function(index, wordPicArticle) {
            	$wordPic.append("<li>"
    	            	+"<a href='http://shui.rrs.com/article/articleDetail/" + wordPicArticle.id + ".html' target='_blank'>"
    	            	+"<img width='100' height='75' src='" + wordPicArticle.imageUrl + "' original='" + wordPicArticle.imageUrl + "' >"
    	            	+"</a>"
    	            	+"<div class='water-graphic-box'>"
    	            	+"<h4 class='tit'><a href='http://shui.rrs.com/article/articleDetail/" + wordPicArticle.id + ".html' target='_blank'>" + wordPicArticle.title + "</a></h4>"
    	            	+"<p class='info'><a href='http://shui.rrs.com/article/articleDetail/" + wordPicArticle.id + ".html' target='_blank'>" + wordPicArticle.tips + "</a></p>"
    	            	+"<p class='time'>" + wordPicArticle.createTimeDesc.substr(0,10) + "</p>"
    	            	+"</div>"
    	            	+"</li>");	
            })
            
            $.each(wordArticleList, function(index, wordArticle) {
            	$wordArticle.append("<li> ▪ <a target='_blank' href='http://shui.rrs.com/article/articleDetail/" + wordArticle.id + ".html'>" + wordArticle.title + "</a></li>");
            })
        }
    };

    rotateAngle.init();

    $("#district_options").bind("mouseover", function() {
        isOnPage = true;
    });
    $("#district_options").bind("mouseout", function() {
        isOnPage = false;
    });

    //小区搜索框
    $("#text_search").bind("keyup", function(e) {

        if ($('#county')[0].selectedIndex === 0) {
        	return false;
        }

        if (jQuery.trim($('#text_search').val())==='') {
        	return false;
        }

        e = e ? e : window.event;
        if (e.keyCode == 13) {
        	if (jQuery.trim(jQuery("#text_search").val()) == "") {
                return;
            }
            else {
                var county = encodeURI($("#county").find("option:selected").text());
                var POI_Name = encodeURI($.trim($("#text_search").val()));
                if (POI_Name != inputLenth || county != inputCounty) {
                	rotateAngle.searchVillage();
                }
            }
        }
        else {
            return;
        }
    });

    $("#text_search").click(function() {

        if ($('#county')[0].selectedIndex === 0) {
        	return false;
        }

        if (jQuery.trim($('#text_search').val())==='') {
        	return false;
        }

        var county = encodeURI($("#county").find("option:selected").text());
        var POI_Name = encodeURI($.trim($("#text_search").val()));
        
        if (POI_Name != inputLenth || county != inputCounty ) {
        	rotateAngle.searchVillage();
        }
        else {
            if ($.trim($("#district_options").html()).length > 0) {
                $("#district_options").css("display", "block");
            }
            else {
                $("#district_options").css("display", "none");
            }
        }
    });

    $("#text_search").focus(function() {

        if ($('#county')[0].selectedIndex === 0) {
        	return false;
        }

        if (jQuery.trim($('#text_search').val())==='') {
        	return false;
        }

        var county = encodeURI($("#county").find("option:selected").text());
        var POI_Name = encodeURI($.trim($("#text_search").val()));
        
        if (POI_Name != inputLenth || county != inputCounty ) {
        	rotateAngle.searchVillage();
        }
        else {
            if ($.trim($("#district_options").html()).length > 0) {
                $("#district_options").css("display", "block");
            }
            else {
                $("#district_options").css("display", "none");
            }
        }
    });

    $("#text_search").blur(function() {
        if (isOnPage == false) {
            $("#district_options").css("display", "none");
        }

      if ($(this).val() !== '') {
        $('.query-water-area').find('.error').hide();
      }
    });


    $('#text_search').bind('input', function (){

        if ($('#county')[0].selectedIndex === 0) {
        	return false;
        }

        if (jQuery.trim($('#text_search').val())==='') {
        	return false;
        }

        var county = encodeURI($("#county").find("option:selected").text());
        var POI_Name = encodeURI($.trim($("#text_search").val()));

        if (POI_Name != inputLenth || county != inputCounty ) {
        	$("#district_options").empty();
        	rotateAngle.searchVillage();
        }
        else {
            if ($.trim($("#district_options").html()).length > 0) {
                $("#district_options").css("display", "block");
            }
            else {
                $("#district_options").css("display", "none");
            }
        }

    });

    $('#text_search').bind('propertychange', function() {

        if ($('#county')[0].selectedIndex === 0) {
        	return false;
        }

        if (jQuery.trim($('#text_search').val())==='') {
        	return false;
        }

        var county = encodeURI($("#county").find("option:selected").text());
        var POI_Name = encodeURI($.trim($("#text_search").val()));

        if (POI_Name != inputLenth || county != inputCounty ) {
        	rotateAngle.searchVillage();
        }
        else {
            if ($.trim($("#district_options").html()).length > 0) {
                $("#district_options").css("display", "block");
            }
            else {
                $("#district_options").css("display", "none");
            }
        }
    });

	$(".js-poiName").click(function(){
		$("#text_search").val(this.text());
		$("#district_options").css("display", "none");
	});

    $('#js-reset').click(function() {
    	
    	$('.beforecheck').css('display', 'block');
    	$('.aftercheck').css('display', 'none');
    	
    	rotateAngle.setRotate('#js-rotate',0);
        return false;
    });
    
    $('#js-dueMember').click(function() {
    	var cityCode = $('#city-code').val();
    	if(cityCode == "" || cityCode == null){
    		cityCode = "370200";
    	}else if(cityCode == "110000" ||cityCode == "120000" ||cityCode == "310000" ||cityCode == "500000" ){
    		cityCode = parseInt(cityCode) + 100;
    	}
    	var cityName = $('#city').html();
    	var desUrl = rrs.baseDomain + "ixv5/getExperienceByCity?cityCode="+cityCode+'&rnd=' + Math.random();
    	$.getScript(desUrl);
    	return false;
    	$.ajax({
       	    type: 'get',   
       		url:desUrl,
       		dataType: "jsonp",
       		cache: false,    		
       		async:false,
       		success: function(data, status){
    	     	$('#dueMemberSendSms').html(data);
    	     	$('#js_dueCity').html(cityName);
    	     	$('#dueMemberSendSms').show();
           },
          error: function(XMLHttpRequest, textStatus, exception){
          	alert(XMLHttpRequest.status+','+XMLHttpRequest.readyState+','+textStatus);
              alert(msgAjaxErrorForRequest); 
          }
       });	
        return false;
    });
    
    $('#bpp').click(function() {
    	window.open(rrs.ehaierBaseDomain+"bpp/index.html");  
    });

}(jQuery));

function selectDistrict(POI_Name){
	$("#text_search").val(POI_Name);
	$("#district_options").css("display", "none");
}